package com.ruoyi.system.unitl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.domain.Video;
import com.ruoyi.system.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.concurrent.TimeUnit;


// 基于 Java 实现的 HTTP 基本认证示例，使用 RTC 的服务端 RESTful API
@RestController
@RequestMapping("/Recording")
public class Base64Encoding {
    //获取录制id
    @Value("${Recording.customerKey}")
    private String customerKey;

    @Value("${Recording.customerSecret}")
    private String customerSecret;

    @Value("${Recording.accessKey}")
    private String accessKey;

    @Value("${Recording.secretKey}")
    private String secretKey;

    @Autowired
    private RedisService redisService;
    @Autowired
    private IVideoService videoService;

    //获取录播id
    @RequestMapping(path ="/getresourceId",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getresourceId(String cname,String uid) throws Exception {
  /*      cname = "TextChannelName1";
        uid = "1235";*/
        // 客户 ID
        final String customerKey = "66f13406301a437ab36e849522fcd1e9";
        // 客户密钥
        final String customerSecret = "9649c997997e447c862e43ec0c83303b";

        // 拼接客户 ID 和客户密钥并使用 base64 编码
        String plainCredentials = customerKey + ":" + customerSecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // 创建 authorization header
        String authorizationHeader = "Basic " + base64Credentials;

        JSONObject jsonObject = JSONUtil.createObj();
        JSONObject object = JSONUtil.createObj();
        object.set("resourceExpiredHour",24);
        object.set("scene",0);
        jsonObject.set("cname",cname);
        jsonObject.set("uid",uid);
        jsonObject.set("clientRequest",object);

        String authorization = HttpRequest.post("https://api.agora.io/v1/apps/9a005a1f8e0347ec905f2f784cb27b9a/cloud_recording/acquire")
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .body(jsonObject.toString()).execute().body();

        JSONObject jsonObject1 = JSONUtil.parseObj(authorization);
        String resourceId = jsonObject1.getStr("resourceId");
        System.out.println(resourceId);
        return modeStart(resourceId,cname,uid);
    }


    //开始录制
    public JSONObject modeStart(String resourceId,String cname,String uid) throws  Exception{
/*        String cname = RandomUtil.randomNumbers(6);
        String uid = RandomUtil.randomString("123456789",4);*/
        JSONObject jsonObject = JSONUtil.createObj();
        JSONObject clientRequest = JSONUtil.createObj();
        clientRequest.set("clientRequest",jsonObject);
        clientRequest.set("cname",cname);
        clientRequest.set("uid",uid);
        /*jsonObject.set("token",this.getChannelKey(cname,Long.valueOf(uid)).getData());*/

        JSONObject recordingConfig = JSONUtil.createObj();
        recordingConfig.set("channelType",1);
        recordingConfig.set("subscribeUidGroup",3);
        /*recordingConfig.set("streamTypes",2);*/
        jsonObject.set("recordingConfig",recordingConfig);

        JSONObject transcodingConfig = JSONUtil.createObj();
        transcodingConfig.set("width",1920);
        transcodingConfig.set("height",1080);
        transcodingConfig.set("fps",15);
        transcodingConfig.set("bitrate",4160);
        recordingConfig.set("transcodingConfig",transcodingConfig);

/*        JSONObject snapshotConfig = JSONUtil.createObj();
        snapshotConfig.set("captureInterval",5);
        JSONArray array = JSONUtil.createArray();
        array.add("jpg");
        snapshotConfig.set("fileType",array.toArray());
        jsonObject.set("snapshotConfig",snapshotConfig);*/

        JSONObject storageConfig = JSONUtil.createObj();
        storageConfig.set("vendor",2);
        storageConfig.set("region",3);
        storageConfig.set("bucket","ybc-live");
        storageConfig.set("accessKey","LTAI5tFgLF42YVQW644tmrco");
        storageConfig.set("secretKey","4wV2aA6BX6Xex1zIMyRAQmLY9O0cPD");
        JSONArray fileNamePrefix = JSONUtil.createArray();
        fileNamePrefix.add("Live");
        storageConfig.set("fileNamePrefix",fileNamePrefix.toArray());

        jsonObject.set("storageConfig",storageConfig);
        String url = "https://api.agora.io/v1/apps/"+ "9a005a1f8e0347ec905f2f784cb27b9a" +"/cloud_recording/resourceid/"+resourceId+"/mode/"+ "mix" +"/start";
        System.out.println(clientRequest);
        String authorization = HttpRequest.post(url)
                .header("Authorization", "Basic NjZmMTM0MDYzMDFhNDM3YWIzNmU4NDk1MjJmY2QxZTk6OTY0OWM5OTc5OTdlNDQ3Yzg2MmU0M2VjMGM4MzMwM2I=")
                .header("Content-Type", "application/json;charset=utf-8")
                .body(clientRequest.toString()).execute().body();
        JSONObject object = JSONUtil.createObj();
        JSONObject parseObj = JSONUtil.parseObj(authorization);
        object.set("resourceId",parseObj.getStr("resourceId"));
        object.set("sid",parseObj.getStr("sid"));
        object.set("uid",uid);
        object.set("cname",cname);
        redisService.setCacheObject(cname,object,Long.valueOf(5), TimeUnit.MINUTES);
        return parseObj;
    }
    //结束录制
    @RequestMapping(path ="/modeStop",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject modeStop(String cname,String uid) throws  Exception{
/*        cname = "TextChannelName1";
        uid = "1235";*/
        JSONObject stop = JSONUtil.createObj();
        stop = redisService.getCacheObject(cname);

        JSONObject jsonObject = JSONUtil.createObj();
        JSONObject clientRequest = JSONUtil.createObj();

        clientRequest.set("async_stop",false);
        jsonObject.set("cname",cname);
        jsonObject.set("uid",uid);
        jsonObject.set("clientRequest",clientRequest);

        System.out.println(uid);
        String url = "https://api.agora.io/v1/apps/"+ "9a005a1f8e0347ec905f2f784cb27b9a" +"/cloud_recording/resourceid/"+stop.getStr("resourceId")+
                "/sid/" +stop.getStr("sid")+"/mode/mix/stop";

        String body = HttpRequest.post(url)
                .header("Authorization", "Basic NjZmMTM0MDYzMDFhNDM3YWIzNmU4NDk1MjJmY2QxZTk6OTY0OWM5OTc5OTdlNDQ3Yzg2MmU0M2VjMGM4MzMwM2I=")
                .header("Content-Type", "application/json;charset=utf-8")
                .body(jsonObject.toString()).execute().body();
        JSONObject parseObj = JSONUtil.parseObj(body);
        System.out.println(parseObj.getJSONObject("serverResponse").getStr("fileList"));

        Video video = new Video();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        video.setVideoAddress("https://ybc-live.oss-cn-beijing.aliyuncs.com/" + parseObj.getJSONObject("serverResponse").getStr("fileList"));
        video.setVideoType("Recording");
        video.setVideoTilie("录播"+cname+df.format(new Date()));

        videoService.insertVideo(video);

        return parseObj;
    }



}